package com.adong.crowd.handler;

import com.adong.crowd.api.MyRedisRemoteService;
import com.adong.crowd.api.MySQLRemoteService;
import com.adong.crowd.config.TextMessageProperties;
import com.adong.crowd.constant.CrowdConstant;
import com.adong.crowd.entity.po.MemberPO;
import com.adong.crowd.entity.vo.MemberLoginVO;
import com.adong.crowd.entity.vo.MemberVO;
import com.adong.crowd.util.CrowdUtil;
import com.adong.crowd.util.ResultEntity;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
public class MemberHandler {

    @Autowired
    private TextMessageProperties textMessage;

    @Autowired
    private MyRedisRemoteService myRedisRemoteService;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    /**
     * 点击发送验证码,发送验证码,验证码存入Redis
     *
     * @param phoneNum
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/member/send/short/message")
    public ResultEntity<String> sendMessage(@RequestParam("phoneNum") String phoneNum) {
        // 通过工具类发送短信到手机
        ResultEntity<String> sendMessageResultEntity = CrowdUtil.sendTextMessage(textMessage.getHost(), textMessage.getPath(), textMessage.getPath(), phoneNum, textMessage.getTemplateID(), textMessage.getAppCode());

        // 通过短信判断结果
        if (ResultEntity.SUCCESS.equals(sendMessageResultEntity.getResult())) {
            // 发送成功获取验证码存入Redis
            String code = sendMessageResultEntity.getData();
            // 拼前缀
            String key = CrowdConstant.REDIS_CODE_PREFIX + phoneNum;
            // 调用远程接口实现保存验证码

            ResultEntity<String> saveCodeResultEntity = myRedisRemoteService.setRedisKeyValueRemoteWithTimeout(key, code, 15, TimeUnit.MINUTES);

            if (ResultEntity.SUCCESS.equals(saveCodeResultEntity.getResult())) {
                return ResultEntity.successWithoutData();
            } else {
                return saveCodeResultEntity;
            }
        } else {
            return sendMessageResultEntity;
        }
    }

    /**
     * 用户注册按钮的操作
     *
     * @param memberVo
     * @param modelMap
     * @return
     */
    @RequestMapping("/auth/do/member/register")
    public String register(MemberVO memberVo, ModelMap modelMap) {

        // 获取登录的手机号
        String phoneNum = memberVo.getPhoneNum();

        // 获取Redis中手机号的value
        String RedisKey = CrowdConstant.REDIS_CODE_PREFIX + phoneNum;
        ResultEntity<String> redisResultEntity = myRedisRemoteService.getRedisStringValueByKeyRemote(RedisKey);

        // 检查操作有效
        // 获取操作的结果
        String result = redisResultEntity.getResult();

        // 没有查询到,获取结果失败
        if (ResultEntity.FAILED.equals(result)) {
            modelMap.addAttribute("message", "请发送验证码");
            return "member-reg";
        }

        // 获取Redis中的短信验证码
        String redisMessageCode = redisResultEntity.getData();
        if (redisMessageCode == null) {
            modelMap.addAttribute("message", "验证码过期,请重新获取");
            return "member-reg";
        }
        // 表中中提交的短信验证码
        String formMessageCode = memberVo.getCode();

        // 判断两个是否一样
        if (!Objects.equals(redisMessageCode, formMessageCode)) {
            modelMap.addAttribute("message", "验证码错误");
            return "member-reg";

        }
        // 验证码液一致,删除Redis中的验证码
        ResultEntity<String> removeResultEntity = myRedisRemoteService.removeRedisKeyRemote(RedisKey);
        // 执行密码加密
        BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = memberVo.getUserpswd();

        String encode = cryptPasswordEncoder.encode(password);
        memberVo.setUserpswd(encode);

        // 创建po对象存储到数据库
        MemberPO memberPO = new MemberPO();

        // 将页面中注册的对象,属性复制到po对象中
        BeanUtils.copyProperties(memberVo, memberPO);

        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveMember(memberPO);
        // MySQL据库保存失败
        if (ResultEntity.FAILED.equals(saveResultEntity.getResult())) {
            modelMap.addAttribute("message", "注册保存失败,请重新试试,谢谢");
            return "member-reg";
        }

        return "redirect:http://localhost:80/auth/member/to/login/page";
    }

    /**
     * 登录按钮的操作
     */
    @RequestMapping("/auth/member/do/login")
    public String login(@RequestParam("loginacct") String loginacct, @RequestParam("userpswd") String userpswd, ModelMap map, HttpSession session) {
        // 根据loginacct查询账户
        ResultEntity<MemberPO> memberPOByLoginAcctResultEntity = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);
        if (ResultEntity.FAILED.equals(memberPOByLoginAcctResultEntity.getResult())) {
            map.addAttribute("message", "账户或者密码错误");
            return "member-login";
        }
        // 获取结果,封装对象
        MemberPO memberPO = memberPOByLoginAcctResultEntity.getData();
        if (memberPO == null) {
            map.addAttribute("message", "账户或者密码错误");
            return "member-login";
        }
        // 获取数据库中密码
        String userpswdDatabase = memberPO.getUserpswd();
        BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean result = cryptPasswordEncoder.matches(userpswd, userpswdDatabase);

        if (!result) {
            map.addAttribute("message", "账户或者密码错误");
            return "member-login";
        }
        MemberLoginVO memberLoginVO = new MemberLoginVO(memberPO.getId(), memberPO.getUsername(), memberPO.getEmail());
        session.setAttribute("loginMember", memberLoginVO);
        return "redirect:http://localhost:80/auth/member/to/center/page";
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/auth/member/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:http://localhost:80/auth/member/to/login/page";
    }
}
